/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ValidatePaymentFrame.java
 *
 * Created on Jan 19, 2010, 12:59:30 AM
 */

package org.acmwustl.bubble.gui;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.SwingWorker;
import org.acmwustl.bubble.controllers.PaymentController;
import org.acmwustl.bubble.gui.dialogs.NotAnOfficerDialog;
import org.acmwustl.bubble.logic.ConnectionManager;
import org.acmwustl.bubble.util.PriceToString;
import org.acmwustl.bubble.windowutils.WindowUtils;

/**
 *
 * @author tyler
 */
public class ValidatePaymentFrame extends javax.swing.JFrame
implements KeyListener {

    private final PaymentController myController;
    private String officerIDCode = "";
    private String paymentIDCode;
    private int amount;

    private boolean ignoreInput = false;

    /** Creates new form ValidatePaymentFrame */
    public ValidatePaymentFrame(String keyIDCode, int paymentInCents, PaymentController pc) {
        initComponents();
        myController = pc;
        this.paymentIDCode = keyIDCode;
        this.amount = paymentInCents;

        setSize(new Dimension(1024,768));
        WindowUtils.centerWindow(this);

        //TODO convert keyIDCode to a name
        aboutLabel.setText(aboutLabel.getText().replace("[YOUR NAME]",
                ConnectionManager.getInstance().getName(keyIDCode)));
        aboutLabel.setText(aboutLabel.getText().replace("[PRICE]",
                PriceToString.getPriceAsString(paymentInCents)));

        getRootPane().addKeyListener(this);
        getRootPane().requestFocus();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        aboutLabel = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setUndecorated(true);

        jLabel1.setFont(new java.awt.Font("DejaVu Sans", 0, 48));
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Officer Required");

        aboutLabel.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        aboutLabel.setText("<html>Officer, please swipe your card to confirm that <i>[YOUR NAME]</i> has paid the amount of <i>[PRICE]</i> to the ACM. Please place the money in the closet. <b>By swiping your card, you are verifying that this payment is valid.</b></html>");

        jButton1.setText("Cancel Payment");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(aboutLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 307, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 167, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 811, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(aboutLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(316, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        dispose();
    }//GEN-LAST:event_jButton1ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel aboutLabel;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    // End of variables declaration//GEN-END:variables

    public void keyTyped(KeyEvent ke) {
        if(!ignoreInput) {
            officerIDCode += ke.getKeyChar();
            if (officerIDCode.length() == 19) {
                if(officerIDCode.matches(";\\d{5}=\\d{11}\\?")) {
                    dispose();
                    if (!myController.authorizePayment(officerIDCode, paymentIDCode, amount)) {
                        dispose();
                        Toolkit.getDefaultToolkit().beep();
                        new NotAnOfficerDialog(this, true).setVisible(true);
                    }
                } else {
                    officerIDCode = "";
                    new IgnoreInputTimer().execute();
                    Toolkit.getDefaultToolkit().beep();
                }
            }
        }
    }
    public void keyPressed(KeyEvent ke) {}
    public void keyReleased(KeyEvent ke) {}

    private class IgnoreInputTimer extends SwingWorker {

        private long time = 300;
        private boolean running = true;
        private long lastMillis;

        public IgnoreInputTimer() {
            ignoreInput = true;
        }

        @Override
        protected Object doInBackground() throws Exception {
            lastMillis = System.currentTimeMillis();
            while(running) {
                time -= (System.currentTimeMillis() - lastMillis);
                lastMillis = System.currentTimeMillis();
                if(time <= 0) {
                    ignoreInput = false;
                    running = false;
                    System.err.println("DONE!");
                }
                else
                    Thread.sleep(100);
            }
            return null;
        }
    }
}
